package com.BEASTMODE.games;

import java.util.List;

import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnTouchListener;

public class GameThread extends Thread implements OnTouchListener
{
	private List<MotionEvent> _inputStack;
	private GridWorksView _gwv;
	private boolean _running = false;
	
	public GameThread(GridWorksView gw)
	{
		_gwv = gw;
		gw.setOnTouchListener(this);
	}
	
	public void Start()
	{
		_running = true;
		start();
	}
	
	public void Stop()
	{
		_running = false;
	}
	
	@Override
	public void run()
	{
		long thisTime = System.currentTimeMillis(), lastTime = thisTime;
		// current state
		//  set this here to the correct initial state
		GameState cs = SplashState._highlander;
		cs.Enter();
		// draw info
		Canvas c = null;
		SurfaceHolder sh = null;
		while (_running)
		{
			thisTime = System.currentTimeMillis();
			cs.Input(_inputStack);
			switch (cs.Update((thisTime - lastTime)/1000.0f))
			{
				case GS_MAINMENU:
					break;
				case GS_GAME:
					cs.Leave();
					cs = PlayState._highlander;
					cs.Enter();
					break;
				case GS_QUIT:
					cs.Leave();
					_running = false;
					break;
			}
			try
			{
				sh = _gwv.getHolder();
				c = sh.lockCanvas();
				synchronized(sh)
				{
					//_gwv.onDraw(c);
				}
			}
			finally
			{
				if (sh != null)
					sh.unlockCanvasAndPost(c);
			}
			lastTime = thisTime;
		}
	}

	public boolean onTouch(View arg0, MotionEvent arg1)
	{
		_inputStack.add(arg1);
		return true;
	}
}
